package com.manager.common.pdf;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.util.Arrays;

public class File2PdfUtils {

    //doc,dox,xls, xlxs,ppt, pptx ，文本格式
    private static String[] fileSuffix = {".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt"};

    private static String licenseStr =
            "<License>\n" +
                    "  <Data>\n" +
                    "    <Products>\n" +
                    "      <Product>Aspose.Total for Java</Product>\n" +
                    "      <Product>Aspose.Words for Java</Product>\n" +
                    "    </Products>\n" +
                    "    <EditionType>Enterprise</EditionType>\n" +
                    "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                    "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
                    "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                    "  </Data>\n" +
                    "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                    "</License>";


    private static void excelLicense() throws Exception {
        InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
        com.aspose.cells.License excelLicense = new com.aspose.cells.License();
        excelLicense.setLicense(license);
    }


    private static void pptLicense() throws Exception {
        InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
        com.aspose.slides.License ppt = new com.aspose.slides.License();
        ppt.setLicense(license);
    }

    private static void wordLicense() throws Exception {
        InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
        License asposeLic = new License();
        asposeLic.setLicense(license);
    }

    private static void excel2pdf(String filePath, String pdfFilePath) {
        try {
            excelLicense();
            File pdfFile = new File(pdfFilePath);// 输出路径
            com.aspose.cells.Workbook wb = new Workbook(filePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);

            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);

            wb.save(fileOS, pdfSaveOptions);
            fileOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void ppt2Pdf(String filePath, String pdfFilePath) {
        try {
            pptLicense();
            InputStream slides = new FileInputStream(filePath);
            Presentation pres = new Presentation(slides);
            File pdfFile = new File(pdfFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void word2Pdf(String filePath, String pdfFilePath) {
        FileOutputStream fileOS = null;

        try {
            wordLicense();
            Document doc = new Document(filePath);
            fileOS = new FileOutputStream(new File(pdfFilePath));
            // 保存转换的pdf文件
            doc.save(fileOS, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOS != null) {
                    fileOS.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean canConvert(String fileName) {
        for (String suffix : fileSuffix) {
            if (fileName.toLowerCase().endsWith(suffix)) {
                return true;
            }
        }
        return false;
    }

    public static String getSuffix() {
        return String.join(",", Arrays.asList(fileSuffix));
    }

    /**
     * 可以将doc,dox,xls, xlxs,ppt, pptx和文本格式的文件转为pdf
     * windows, linux 均可以使用
     **/
    public static String file2Pdf(String resourcePath) throws Exception {
        String suffix = resourcePath.substring(resourcePath.lastIndexOf(".") + 1, resourcePath.length());
        String pdfTargetPath = resourcePath.substring(0, resourcePath.lastIndexOf(".")) + ".pdf";
        File file = new File(resourcePath);

        if (!file.exists()) {
            return null;
        }

        file = new File(pdfTargetPath);
        if (file.exists()) {
            return pdfTargetPath;
        }

        try {

            System.out.println(resourcePath);
            System.out.println(pdfTargetPath);

            if ("doc".equals(suffix) || "docx".equals(suffix)) {
                File2PdfUtils.word2Pdf(resourcePath, pdfTargetPath);
            } else if ("xls".equals(suffix) || "xlsx".equals(suffix)) {
                File2PdfUtils.excel2pdf(resourcePath, pdfTargetPath);
            } else if ("ppt".equals(suffix) || "pptx".equals(suffix)) {
                File2PdfUtils.ppt2Pdf(resourcePath, pdfTargetPath);
            } else {
                JacobUtils.txtToPdf(resourcePath, pdfTargetPath);
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
        return pdfTargetPath;
    }

    public static boolean wordToHtml(String docFile, String htmlFilePath) {
        try {
            wordLicense();
            Document doc = new Document(docFile);
            convertWordToHtmlOutputStream(doc,htmlFilePath);
            return true;
        } catch (Exception e) {
            System.err.println("转换 Word 为 HTML 时出错：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


    public static boolean htmlToWord(String htmlPath,String docPath) {
        try {
            wordLicense();
            Document document = new Document(htmlPath);
           // document.getFirstSection().getPageSetup().setPageWidth(700);
            document.save(docPath,SaveFormat.DOCX);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    private static String setLinkStyle(String htmlContent) {

        String customCss = "a { color: blue !important; text-decoration: underline !important; }";

        customCss += " a span { color: blue !important; }";

        if (htmlContent.contains("<head>")) {
            htmlContent = htmlContent.replace("<head>", "<head><style>" + customCss + "</style>");
        } else {
            // 如果没有<head>标签，则创建<head>标签
            htmlContent = "<head><style>" + customCss + "</style></head>" + htmlContent;
        }

        return htmlContent;
    }

    private static void convertWordToHtmlOutputStream(Document doc, String htmlFIlePath) throws Exception {

        ByteArrayOutputStream htmlOutputStream = new ByteArrayOutputStream();
        HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.HTML);

      /*// 页面布局和格式保持
        saveOptions.setExportHeadersFootersMode(ExportHeadersFootersMode.PER_SECTION);
        saveOptions.setExportPageSetup(false);*/

        // 图片处理
        saveOptions.setExportImagesAsBase64(true);
        saveOptions.setScaleImageToShapeSize(true);
        saveOptions.setImageResolution(150);
        saveOptions.setUseAntiAliasing(true);
        saveOptions.setUseHighQualityRendering(true);

      /*  // 样式和CSS
        saveOptions.setCssStyleSheetType(CssStyleSheetType.EMBEDDED);
        saveOptions.setPrettyFormat(true);
*/
        // 链接和图像路径
        saveOptions.setExportOriginalUrlForLinkedImages(true);

        doc.save(htmlOutputStream, saveOptions);

        String htmlContent = htmlOutputStream.toString("UTF-8");
        //htmlContent = setLinkStyle(htmlContent);

       // htmlContent = fixMissingAlignment(htmlContent);

        FileOutputStream fileOutputStream = new FileOutputStream(htmlFIlePath);
        fileOutputStream.write(htmlContent.getBytes("UTF-8"));
        fileOutputStream.close();
    }


    private static String fixMissingAlignment(String htmlContent) {
        org.jsoup.nodes.Document document = Jsoup.parse(htmlContent);

        // 选中所有 <td>、<th>、<p> 标签
        Elements cells = document.select("td, th, p");

        // 遍历标签，检查是否已设置 text-align 样式
        for (Element cell : cells) {
            if (cell.tag().getName().toLowerCase().equals("td")) {
                cell.attr("contenteditable", "true");
            }
            String style = cell.attr("style");
            if (!style.toLowerCase().contains("text-align")) {
                // 如果没有设置，则添加 text-align: left;
                cell.attr("style", "text-align: left;" + style);
            }
        }

        return document.outerHtml();
    }

    public static void main(String[] args) throws Exception {
        String filePath1 = "E:\\360MoveData\\Users\\liuhj\\Desktop\\88b2e70e2cdc4fd986838f41db01644c.docx";
        String filePath2 = "E:\\360MoveData\\Users\\liuhj\\Desktop\\2.html";
       // File2PdfUtils.wordToHtml(filePath1,filePath2);
        JacobUtils.wordToHtml(filePath1,filePath2);
        String filePath3 = "E:\\360MoveData\\Users\\liuhj\\Desktop\\test.docx";
        File2PdfUtils.htmlToWord(filePath2,filePath3);
    }
}
